import functools
from datetime import datetime, timedelta

from SpiderSession import SpiderSession
from config import global_config
from sh_logger import logger
from util import parse_json, wait_some_time
from timer import Timer


class Seckill(object):
    def __init__(self):
        self.spider_session = SpiderSession()
        self.spider_session.load_cookies_from_local()

        # 初始化信息

        self.seckill_num = 2
        self.seckill_init_info = dict()
        self.seckill_url = dict()
        self.seckill_order_data = dict()
        self.timers = Timer()

        self.session = self.spider_session.get_session()
        self.user_agent = self.spider_session.user_agent
        self.nick_name = None

        self.running_flag = True

        self.code = global_config.getRaw('config', 'code')
        self.ukey = global_config.getRaw('config', 'ukey')
        self.tokenid = global_config.getRaw('config', 'tokenid')
        self.productID = global_config.getRaw('config', 'product_id')
        # 抢购次数
        self.repeat_times = 0

    def check_login_and_jdtdufp(func):
        """
        用户登陆态校验装饰器。若用户未登陆，则调用扫码登陆
        """

        @functools.wraps(func)
        def new_func(self, *args, **kwargs):
            if not self.qrlogin.is_login:
                logger.info("{0} 需登陆后调用，开始扫码登陆".format(func.__name__))
                self.login_by_qrcode()
            if not self.jd_tdufp.is_init:
                self.jd_tdufp.init_jd_tdudfp()
            return func(self, *args, **kwargs)

        return new_func

    def get_signature(self):
        """获取签名信息"""
        url = 'https://sapph5api.leqilucky.com/WechatService/WxJsSignatureInfo'
        payload = {
            'uname': 'h5',
            'ukey': self.ukey,
            'tokenid': self.tokenid,
            'url': 'https://sapph5.lqlucky.com/?code={}&state=STATE'.format(self.code),
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.get(url=url, params=payload, headers=headers)
        resp_json = parse_json(resp.text)
        # nonceStr = resp_json.get('nonceStr')
        signature = resp_json.get('signature')
        logger.info('签名: %s', signature)
        # {
        #     "timestamp": 1700480552,
        #     "nonceStr": "0be24c1fb22b4cf9846bea07ae15c8a1",
        #     "signature": "a6567737a1dca27974d3dcf644f317cb2a395304"
        # }
        return signature

    def get_sale_centre(self):
        """获取零元购列表"""
        url = 'https://sapph5api.leqilucky.com/Sale/Sale/SaleCentre'
        post_data = {
            'uname': 'h5',
            'ukey': self.ukey,
            'tokenid': self.tokenid,
            'DropDown': False,
            'SAPPHomeSortType': 0,
            'IsHomePage': True,
            'CategoryLeve1ID': '',
            'ShopType': ''
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.post(url=url, data=post_data, headers=headers)
        resp_json = parse_json(resp.text)
        # nonceStr = resp_json.get('nonceStr')
        # signature = resp_json.get('signature')
        logger.info(resp_json)
        return resp

    def get_product(self):
        """获取商品信息"""
        url = 'https://sapph5api.leqilucky.com/NoAuth/SaleIndex/SaleProductInfo'
        payload = {
            'uname': 'h5',
            'ukey': self.ukey,
            'tokenid': self.tokenid,
            'productID': self.productID,
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.get(url=url, params=payload, headers=headers)
        resp_json = parse_json(resp.text)
        logger.info(resp_json)
        # {
        #     "IsAuditing3": false,
        #     "SaleProductInfo": {
        #         "ProductID": "16d1371c-8d05-4cab-afc2-c79ce447e29f",
        #         "WAPPicUrl": "http://youp-read.leqilucky.com/upaiyun/Product/20231116/4812455961642519447.png",
        #         "TitleShort": "【安克大牌】苹果超快充数据线",
        #         "ProductPrice": 13.90,
        #         "SaleDiscountPrice": 0.00,
        #         "IsSale": true,
        #         "DescText": "\u003cp\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN01h2zfFb1CyHt8QEYJc_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN017HNjFd1CyHsxz6As9_!!2215810050149.png\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01uELgDL1CyHszl9BXP_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i1/2215810050149/O1CN01CTT91R1CyHt5CO9Is_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01ZMnzal1CyHt1nxIaE_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN01PjSsvW1CyHsxz2cV0_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i1/2215810050149/O1CN01VtOhIG1CyHt7aN9CY_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN010ZzRtQ1CyHt8QDocF_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01VA21WS1CyHt6h1hmZ_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01ugA8qD1CyHt5CKONH_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN01h2qAJ21CyHszl9NzN_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01TOU4o51CyHsxz3MEp_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN01nqAjwd1CyHt4AtJdf_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i1/2215810050149/O1CN01QEnoKI1CyHszA6VzN_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01LEfRUg1CyHt5CK7kJ_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN018kV6HM1CyHt6h0hO9_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i1/2215810050149/O1CN01PXpdTa1CyHt1lIPbU_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i1/2215810050149/O1CN01aT06ub1CyHt2yYKXf_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i2/2215810050149/O1CN01DrATJa1CyHtMO8np0_!!2215810050149.png\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01dgijzv1CyHstJtvKG_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i3/2215810050149/O1CN01GKgfiJ1CyHt337NCB_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i2/2215810050149/O1CN01K4opSB1CyHt4ArEjs_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003cimg src=\"https://img.alicdn.com/imgextra/i4/2215810050149/O1CN01Xpoc241CyHsxz3pN5_!!2215810050149.jpg\" align=\"absmiddle\"\u003e\u003c/p\u003e",
        #         "ProductItemImgs": [{
        #             "ItemImgID": "553aced2-6518-4856-bb74-f51cda2d04a1",
        #             "Url": "https://img.alicdn.com/bao/uploaded/i3/2215810050149/O1CN01ae6DOF1CyHuYN4204_!!2-item_pic.png",
        #             "Position": 0
        #         }],
        #         "IsRemind": false,
        #         "RemindID": null,
        #         "StockCount": 6,
        #         "IsStockNoZero": true,
        #         "IsFreeCard": true,
        #         "FreeCardNum": 1,
        #         "IsFavorite": false,
        #         "IsScareBuyTime": true,
        #         "ScareBuyNodeList": [{
        #             "GapDay": 0,
        #             "Node": "20:00"
        #         }, {
        #             "GapDay": 0,
        #             "Node": "21:00"
        #         }, {
        #             "GapDay": 0,
        #             "Node": "22:00"
        #         }, {
        #             "GapDay": 0,
        #             "Node": "23:00"
        #         }],
        #         "BuyUserList": [{
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/ia5yDfa2OyRRhm0icFx7PneREl4aY8qs86e0Ak6QMgxdeMQEeFabq3AewrzAes8rAAw1Ap4CK5fWZ2vGk3VXpkicw/132",
        #             "Nick": "寻觅未来",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700480239860)\/",
        #             "TotalSeconds": 311
        #         }, {
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJrul7yN3I8uaxtRqjb65XJkzrsOVzKsRia6olWDTlayBicL8ddO4mdciaF39emFwFuvXHSp7hbStnbg/132",
        #             "Nick": "阿兰",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700479933010)\/",
        #             "TotalSeconds": 618
        #         }, {
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/sFXrgaPvQiaTmrvzHYxgvd2AfdEUdRib4hkJBI56vBONOu06DHWjC0I3cFaPLLc0ib7ZlX9iatvvuoIMBYIN9dIGeA/132",
        #             "Nick": "W.",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700479804113)\/",
        #             "TotalSeconds": 747
        #         }, {
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEKCwhgbRLTKIDSyQDxIPPMSzAsTmlKpIDTv5G0U4ZVEzbXxibhFptW730IaUFCDCIh6jI3PU9Rg9opgecjJl21niamC2GbbD4iafkVcicexafrtSg/132",
        #             "Nick": "明天会更好",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700479218707)\/",
        #             "TotalSeconds": 1333
        #         }, {
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEK20QS1WkINK3BrolZg67Mxjnp1v2pQdRxzFTg8XfibLvPERkfaYibBctdwtrA7LmOHPibTgXwsWJMuP64Jhzy9EibqTC8sEK1sMXA3ZoI8g3Zg8g/132",
        #             "Nick": "安然",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700479054620)\/",
        #             "TotalSeconds": 1497
        #         }, {
        #             "HeadPortraitUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEJT1cne0gDfVVI73KntmFk2pDZSRdMAl1jHXDs6JqAsrv7zefftyh9uZYtH3JxhsFicicCHQ0qzcpeA/132",
        #             "Nick": "七七",
        #             "OrderType": 1,
        #             "FreeCardNum": 1,
        #             "BuyTime": "\/Date(1700478698300)\/",
        #             "TotalSeconds": 1853
        #         }],
        #         "ShowPicUrl": "http://youp-read.leqilucky.com/upaiyun/Product/20231019/5288448336601674096.jpg",
        #         "OrderFreeCardList": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        #         "ShopType": 1,
        #         "PddProductDetailList": null,
        #         "IsNewPerson": true,
        #         "ShopID": "d1044403-75f2-40fa-9997-866d45aa2303"
        #     }
        # }
        return resp

    def check_exist(self):
        """检查是否存在订单"""
        url = 'https://sapph5api.leqilucky.com/Sale/Task/CheckIsExistSOrder'
        post_data = {
            'uname': 'h5',
            'ukey': self.ukey,
            'tokenid': self.tokenid,
            'productId': self.productID,
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.post(url=url, data=post_data, headers=headers)
        resp_json = parse_json(resp.text)
        # nonceStr = resp_json.get('nonceStr')
        logger.info(resp_json)
        # {
        #     "IsExists": false,
        #     "IsThisProduct": false,
        #     "SOStatus": null,
        #     "TaskID": null,
        #     "IsBaseSaleModel": false
        # }
        return resp

    def seckill_canstill_running(self):
        """用config.ini文件中的continue_time加上函数buytime_get()获取到的buy_time，
            来判断抢购的任务是否可以继续运行
        """
        buy_time = self.timers.buy_time
        #buy_time = datetime.strptime(global_config.getRaw('config', 'buy_time'), "%Y-%m-%d %H:%M:%S.%f")
        continue_time = int(global_config.getRaw('config', 'continue_time'))
        stop_time = datetime.strptime(
            (buy_time + timedelta(minutes=continue_time)).strftime("%Y-%m-%d %H:%M:%S.%f"),
            "%Y-%m-%d %H:%M:%S.%f"
        )
        current_time = datetime.now()
        if current_time > stop_time:
            self.running_flag = False
            logger.info('超过允许的运行时间，任务结束。')

    def soho(self):
        """立即兑换"""
        if self.timers.buy_time:
            while self.running_flag:
                self.seckill_canstill_running()
                try:
                    self.timers.start()
                    while self.running_flag:
                        self._soho()
                        self.seckill_canstill_running()
                except Exception as e:
                    logger.info('抢购发生异常，稍后继续执行！', e)
                wait_some_time()
        else:
            logger.info('该商品暂无抢购时间')
    def _soho(self):
        """立即兑换"""
        url = 'https://sapph5api.leqilucky.com/Sale/Task/SoHo'
        post_data = {
            'uname': 'h5',
            'ukey': self.ukey,
            'tokenid': self.tokenid,
            'productId': self.productID,
            'isFreeCard': True,
            'isFirst': True,
            'IsCfmdLimitArea': False,
            'isFreeCardLimitRemind': False
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.post(url=url, data=post_data, headers=headers)
        resp_json = parse_json(resp.text)
        # nonceStr = resp_json.get('nonceStr')
        # 将JSON数据解析为Python字典
        #data_dict = json.loads(resp.text)
        # 获取SearchKey字段的值
        #search_key = data_dict["SoHoInfo"]["SearchKey"]

        self.repeat_times += 1
        if resp_json.get('SoHoInfo'):
            logger.info('第{}次抢购成功，返回信息:{}'.format(self.repeat_times, resp_json))
            self.running_flag = False
            return True
        elif resp_json.get('ErrMsg') == '抱歉哟，名额已被抢光，请选择其他商品':
            logger.info('第{}次抢购失败，返回信息:{}'.format(self.repeat_times, resp_json))
            if self.repeat_times > 50:
                self.running_flag = False
            return False
        else:
            logger.info('第{}次抢购失败，返回信息:{}'.format(self.repeat_times, resp_json))
            # 失败10次后自动结束程序
            if self.repeat_times > 50:
                self.running_flag = False
            # 可能活动还没开始，等待一点时间
            # wait_some_time()
            return False
        # {
        #     "SoHoInfo": {
        #         "PlatformType": 0,
        #         "ProductID": "16d1371c-8d05-4cab-afc2-c79ce447e29f",
        #         "KeywordID": "68709823-2e87-41f8-a2ff-2ead5fcc96af",
        #         "RestCount": 5,
        #         "SearchKey": "苹果15充电线",
        #         "SortType": 0,
        #         "IsFreeShipping": false,
        #         "IsTmall": false,
        #         "IsGiveFI": false,
        #         "ShopName": "安*****店",
        #         "IsOtherApply": false,
        #         "NowTime": "\/Date(1700480666857)\/",
        #         "RelationTime": "\/Date(1700480666857)\/",
        #         "BuyerRelationCount": 1,
        #         "TaskId": "19972015179",
        #         "IsLimitPrice": false,
        #         "LimitLowPrice": null,
        #         "LimitHighPrice": null,
        #         "OrderType": 1,
        #         "SendAddress": null,
        #         "ConfigCondition": null,
        #         "IsFirstBuy": false,
        #         "Remark": null,
        #         "IsBaseSaleModel": false,
        #         "PddSpeciaKeyword": null,
        #         "SearchType": 0,
        #         "IsSwappableKeyword": true
        #     },
        #     "ConfigAccurateMode": true,
        #     "AccurateMode": 0,
        #     "Msg": null,
        #     "ErrMsg": null,
        #     "ErrCode": null,
        #     "ForwardUrl": null,
        #     "Data": null,
        #     "IsError": false
        # }

    def login(self):
        """登录"""
        url = 'https://sapph5api.leqilucky.com/WechatService/Login'
        post_data = {
            'code': self.code,
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'User-Agent': self.user_agent,
            'origin': 'https://sapph5.lqlucky.com',
            'x-requested-with': 'com.tencent.mm',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'Referer': 'https://sapph5.lqlucky.com/',
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
        }

        resp = self.session.post(url=url, data=post_data, headers=headers)
        resp_json = parse_json(resp.text)
        # nonceStr = resp_json.get('nonceStr')
        logger.info(resp_json)
        # {
        #     "Msg": null,
        #     "ErrMsg": null,
        #     "ErrCode": null,
        #     "ForwardUrl": null,
        #     "Data": {
        #         "tokenid": "242ed67521eb1b038f2a86334fb0ccbf",
        #         "isLogin": true,
        #         "hasOrder": false,
        #         "info": {
        #             "HeadPortraitUrl": "http://youp-read.leqilucky.com/upaiyun/Sys/20190716/5074834154138116882.png",
        #             "Nick": "亦如",
        #             "Province": "",
        #             "City": ""
        #         },
        #         "isNewPerson": true,
        #         "newPersonFreeOrderCount": "3"
        #     },
        #     "IsError": false
        # }
        return resp



